package com.itheima.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.itheima.pay.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @Description:
 * @Version: V1.0
 */
@RestController
public class PayController {
    @Autowired
    AlipayConfig alipayConfig;

    @GetMapping("/alipaytest")
    public String alipaytest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(),
                alipayConfig.getAPPID(), alipayConfig.getRSA_PRIVATE_KEY(),
                alipayConfig.getFORMAT(), alipayConfig.getCHARSET(),
                alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGNTYPE());
        //获得初始化的AlipayClient
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setReturnUrl("url");
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", "20220817010101003");  //交易单号
        bizContent.put("total_amount", 0.01); //交易金额 单位：元
        bizContent.put("subject", "餐掌柜-餐饮消费"); //支付备注

        request.setBizContent(bizContent.toJSONString());
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            if(response.isSuccess()){
                System.out.println("调用成功");
                System.out.println(response.getQrCode());
                return response.getQrCode();
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "OK";
    }
}